package com.boarsoft.boar.auth.grafana;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.boarsoft.bean.LogonI;
import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.auth.AuthConfig;
import com.boarsoft.boar.auth.TokenAuth;
import com.boarsoft.common.Util;
import com.boarsoft.common.util.JsonUtil;
import com.boarsoft.web.login.Logined;

@RestController
@RequestMapping("/grafana")
public class GrafanaAuthAction {
	private static final Logger log = LoggerFactory.getLogger(GrafanaAuthAction.class);

	@Autowired
	private TokenAuth tokenAuth;
	// @Autowired
	// private TxtPwdAuth txtPwdAuth;

	/**
	 * 对应 Grafana OAuth2 auth_url
	 * 
	 * @param redirect_uri
	 * @param state
	 * @param code
	 * @return
	 */
	@RequestMapping("/auth.do")
	public void auth(@Logined LogonI<String> logon, HttpServletRequest req, HttpServletResponse res, String redirect_uri,
			String state) {
		String url = "/auth/login.html#/auth/grafana/auth.do?".concat(req.getQueryString());
		log.info(url);
		if (logon == null || Util.strIsEmpty(logon.getToken())) {
			try {
				res.sendRedirect(url);
				return;
			} catch (IOException e) {
				log.error("Error on redirect to {}", url, e);
			}
		}
		log.info(JsonUtil.from(req.getParameterMap()));
		log.info("{}?state={}&code={}", redirect_uri, state, logon.getToken());
		url = String.format("%s?state=%s&code=%s", redirect_uri, state, logon.getToken());
		// url = url.replace(":3000", "");
		log.info(url);
		try {
			res.sendRedirect(url);
		} catch (IOException e) {
			log.error("Error on redirect to {}", url, e);
		}
	}

	/**
	 * 对应 Grafana OAuth2 token_url
	 * 
	 * @return
	 */
	@RequestMapping(value = "/token.do", produces = { "application/json;charset=UTF-8" })
	// @RequestMapping(value = "/token.do")
	@ResponseBody
	public String token(HttpServletRequest req, String code, String grant_type, String client_id, String client_secret) {
		log.info(JsonUtil.from(req.getParameterMap()));
		StringBuilder sb = new StringBuilder();
		sb.append("{ \"access_token\": \"").append(code).append("\"");
		sb.append(", \"token_type\": \"Bearer\"");
		sb.append(", \"refresh_token\": \"").append(code).append("\"");
		sb.append(", \"expires_int\": 60000 }");
		// sb.append("{ \"access_token\": \"").append(code).append("\" }");
		// sb.append("{ access_token: '").append(code).append("'");
		// sb.append(", token_type: 'SSO'");
		// sb.append(", refresh_token: '").append(code).append("'");
		// sb.append(", expires_int: 60000 }");
		// { "access_token": "40286b815374014a0153741fac170001", "token_type":
		// "grafana", "refresh_token": "40286b815374014a0153741fac170001",
		// "expires_int": 60000 }
		log.info(sb.toString());
		return sb.toString();
	}

	/**
	 * 对应 Grafana OAuth2 api_url<br>
	 * 此方法由grafana-server发起而用户非浏览器发起，因此通过 @Logined 无法获取登录信息
	 * 
	 * @param o
	 * @return
	 */
	@RequestMapping(value = "/api", produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public String api(HttpServletRequest req) {
		String auth = req.getHeader("authorization");
		log.info(auth);
		if (Util.strIsEmpty(auth)) {
			return null;
		}
		String[] aa = auth.split(" ");
		if (aa.length < 2) {
			return null;
		}
		try {
			ReplyInfo<Object> ro = tokenAuth.check(aa[1]);
			log.info(JsonUtil.toJSONString(ro));
			if (ro != null && ro.isSuccess()) {
				LogonI<?> logon = (LogonI<?>) ro.getData();
				StringBuilder sb = new StringBuilder();
				sb.append("{ \"Email\": \"").append(logon.getEmail()).append("\"");
				sb.append(", \"Login\": \"").append(logon.getCode()).append("\"");
				sb.append(", \"Name\": \"").append(logon.getName()).append("\" }");
				log.info(sb.toString());
				return sb.toString();
			}
		} catch (Exception e) {
			log.error("Error on check token {}", aa[1], e);
		}
		return "Invalid token";
	}

	/**
	 * 对应 Grafana OAuth2 api_url/orgs<br>
	 * 此方法由grafana-server发起而用户非浏览器发起，因此通过 @Logined 无法获取登录信息
	 * 
	 * @param o
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/api/orgs", produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public String orgs(HttpServletRequest req, @Logined LogonI<String> logon) {
		// 查询用户归属的机构（租户）
		log.info(JSON.toJSONString(logon));
		//
		String auth = req.getHeader("authorization");
		log.info(auth);
		if (Util.strIsEmpty(auth)) {
			return null;
		}
		String[] aa = auth.split(" ");
		if (aa.length < 2) {
			return null;
		}
		try {
			ReplyInfo<Object> ro = tokenAuth.check(aa[1]);
			log.info(JsonUtil.toJSONString(ro));
			if (ro != null && ro.isSuccess()) {
				logon = (LogonI<String>) ro.getData();
				String corpId = logon.getCorpId();
				// String deptId = logon.getDeptId();
				log.info(AuthConfig.getProperty(corpId));
				return AuthConfig.getProperty(corpId);
			}
		} catch (Exception e) {
			log.error("Error on check token {}", aa[1], e);
		}
		return null;
	}
}